package cn.kgc.crowdfundingadmin.controller;

import cn.kgc.crowdfundingadmin.common.ResultEntity;
import cn.kgc.crowdfundingadmin.pojo.Menu;
import cn.kgc.crowdfundingadmin.service.MenuService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class MenuContrller {
    @Resource
    MenuService menuService;

    @RequestMapping("/menu/get/whole/tree")
    public ResultEntity<Menu>  getwholeTree(){
        // 1.查询所有的树形节点用于组装
        List<Menu> menuList=menuService.getAll();
        // 2.将List<Menu>转换为Map<Menu的id,Menu>
        Map<Integer,Menu> menuMap=new HashMap<>();
        for (Menu menu : menuList) {
            menuMap.put(menu.getId(),menu);
        }
        // 3.声明变量用于存储根节点对象
        Menu  rootNode=null;
        for (Menu menu : menuList) {
          //是父节点
            if (menu.getPid()==null){
                rootNode=menu;
                continue;

            }
            //是子节点从menuMap找到父节点，并添加到父节点的子节点集合中
            menuMap.get(menu.getPid()).getChildren().add(menu);

        }
return   ResultEntity.successWithoutData(rootNode);
    }


    ///添加
    @RequestMapping("/menu/save")
    public  ResultEntity<String> saveMenu(Menu menu){
        menuService.saveMenu(menu);
        return  ResultEntity.successWithoutData();
    }
//修改回显 result风格
@RequestMapping("/menu/get/{menuId}")
public ResultEntity<Menu> getMenuById(@PathVariable("menuId") Integer menuId) {

    Menu menu = menuService.getMenuById(menuId);

    return ResultEntity.successWithoutData(menu);
}

         //正式修改
         @RequestMapping("/menu/update")
         public ResultEntity<String> update(Menu menu){
             menuService.update(menu);
             return ResultEntity.successWithoutData();
         }



}
